package com.softjourn.punchcard.activity;

import java.util.concurrent.ExecutionException;

import org.springframework.util.StringUtils;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.softjourn.punchcard.R;
import com.softjourn.punchcard.lib.ApiFunctions;
import com.softjourn.punchcard.lib.NetworkUtil;
import com.softjourn.punchcard.lib.SessionManager;
import com.softjourn.punchcard.model.Client;
import com.softjourn.punchcard.model.ClientResponse;

public class LoginActivity extends ExitDialogSherlockActivity {
	Button btnLogin;
	Button btnLinkToRegister;
	EditText inputEmail;
	EditText inputPassword;
	TextView loginErrorMsg;

	// Session Manager Class
	SessionManager session;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		getSupportActionBar().hide();

		// Session Manager
		session = new SessionManager(LoginActivity.this);

		// Importing all assets like buttons, text fields
		inputEmail = (EditText) findViewById(R.id.loginEmail);
		inputPassword = (EditText) findViewById(R.id.loginPassword);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
		loginErrorMsg = (TextView) findViewById(R.id.login_error);

		// Login button Click Event
		btnLogin.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString();

				Log.d("Button", "Login");
				if (StringUtils.hasText(email) && StringUtils.hasText(password)) {

					if (NetworkUtil
							.isConnectivityActive(getApplicationContext())) {

						ClientResponse punchCardResponse = null;
						try {

							punchCardResponse = new RegisterAsyncTask()
									.execute(email, password).get();

							Log.i("Main", punchCardResponse.toString());
							// check for login response

							if (punchCardResponse.getStatus().equals("OK")) {
								loginErrorMsg.setText("");

								// user successfully logged in
								// Store user details in SQLite Database
								Client client = punchCardResponse.getClient();

								session.createLoginSession(client.getName(),
										client.getUid());

								// Launch Main Screen
								Intent main = new Intent(LoginActivity.this,
										MainActivity.class);

								// Close all views before launching
								// Dashboard

								startActivity(main);

								// Close Login Screen
								finish();

							} else {
								// Error in login
								loginErrorMsg
										.setText(R.string.incorrect_em_pwd);
							}

						} catch (Exception e) {
							// TODO Auto-generated catch block
							showAlertDialog(
									getApplicationContext(),
									getResources().getString(
											R.string.server_error_title),
									getResources().getString(
											R.string.server_error_mess), false);
							e.printStackTrace();
						}
					} else {
						// Error no internet connection
						showAlertDialog(
								getApplicationContext(),
								getResources().getString(
										R.string.no_internet_connection_title),
								getResources().getString(
										R.string.no_internet_connection_mess),
								false);
					}

				} else {
					// Error in login
					loginErrorMsg.setText(R.string.incorrect_em_pwd);
				}

			}
		});

		// Link to Register Screen
		btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				Intent i = new Intent(LoginActivity.this,
						RegisterActivity.class);
				startActivity(i);
				finish();
			}
		});
	}

	private class RegisterAsyncTask extends
			AsyncTask<String, Void, ClientResponse> {

		@Override
		protected ClientResponse doInBackground(String... params) {

			ApiFunctions userFunction = new ApiFunctions(LoginActivity.this);
			try {
				ClientResponse response = userFunction.loginUser(params[0],
						params[1]);
				Log.i("OK", response.toString());
				return response;

			} catch (Exception e) {
				Log.e("EXCEPTION", e.getMessage());
			}

			return null;
		}

	}

}
